package com.usian.controller;

import com.usian.utils.FastDFSClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
public class FastTestController {

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    @RequestMapping("/upload")
    public String upload(MultipartFile file){
        String path = null;
        try {

            //判断文件是否存在
            if (file == null) {
                throw new RuntimeException("文件不存在");
            }
            //获取文件的完整名称
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)) {
                throw new RuntimeException("文件不存在");
            }

            // group1/M00/00/00/wKg6imLE8DeAazNRAAAbjdzIJUU170.jpg
            path = fastDFSClientUtil.uploadFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //return fileServerUrl + path;
        return  fileServerUrl.concat(path);
    }


    @RequestMapping("/delete")
    public String del(String filePath){
        fastDFSClientUtil.delFile(filePath);
        return "delete ok";
    }

    @RequestMapping("/download")
    public void download(String filePath, HttpServletResponse response){
        try {
            // group1/M00/00/00/wKg6imLE8DeAazNRAAAbjdzIJUU170.jpg
            // group1    m00/00/00.......
            String param0 = filePath.substring(0, filePath.indexOf("/"));
            String param1 = filePath.substring(filePath.indexOf("/")+1);
            byte[] bytes = fastDFSClientUtil.download(param0, param1);

            FileOutputStream fileOutputStream = new FileOutputStream("bytes");
            int len = 0;
            fileOutputStream.write(bytes, 0, len);
            fileOutputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
